package com.hxh.spring.cloud.emoticon.produce.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author huangxunhui
 * Date: Created in 2019-05-10 13:48
 * Utils: Intellij Idea
 * Description:
 */
@Slf4j
public class HttpUtil {

    private HttpUtil(){}

    public static String get(String url) {
        // 创建 Client
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 发起请求
        HttpGet httpGet;
        try {
            httpGet = new HttpGet(url.replace(" " , "%20"));

            // 返回数据
            return execute(httpClient,httpGet);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            close(httpClient);
        }
    }


    public static String get(String url , Map<String,String> params){
        // 创建 Client
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建URIBuilder
        URIBuilder uriBuilder;
        try {
            uriBuilder = new URIBuilder(url);

            //设置参数
            params.forEach(uriBuilder::addParameter);
            log.info("URL:{}",uriBuilder.build());

            // 发起请求
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            return execute(httpClient ,httpGet);
        } catch (Exception e) {
            log.error("e", e);
            close(httpClient);
            return null;
        }finally {
            close(httpClient);
        }
    }

    private static void close(CloseableHttpClient httpClient){
        try {
            httpClient.close();
        } catch (IOException e) {
            log.error("e", e);
        }
    }

    private static String execute(CloseableHttpClient httpClient , HttpGet httpGet) throws IOException {
        CloseableHttpResponse response = httpClient.execute(httpGet);

        // 获取状态
        int statusCode = response.getStatusLine().getStatusCode();

        if(statusCode == HttpStatus.SC_OK){
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "utf-8");
        }else{
            log.error("请求出错 code:{} , 错误信息:{}", statusCode , response);
            return null;
        }
    }
}
